package wechat.app.materialManage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import util.DataFormatUtil;
import util.HttpUtil;
import wechat.util.PostFileUtil;
import wechat.app.bean.Result;
import wechat.app.bean.media.*;

import java.io.*;
import java.util.List;

import static wechat.util.PostFileUtil.postFile;

/**
 * Created by Administrator on 2016/3/15.
 */
public class MediaManage {
    /**
     * 媒体文件类型，分别有图片（image）、语音（voice）、视频（video）和缩略图（thumb）
     **/
    public static UploadTempResult uploadTemp(String token, String type, File file) throws IOException {
        return uploadTemp(token, type, file, file.getName());
    }

    public static UploadTempResult uploadTemp(String token, String type, File file, String fileName) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + token + "&type=" + type;
        String res = postFile(url, file, fileName);
        JSONObject result = JSON.parseObject(res);
        return UploadTempResult.create(result);
    }

    public static UploadTempResult uploadTemp(String token, String type, InputStream inputStream, String fileName) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + token + "&type=" + type;
        String res = postFile(url, inputStream, fileName);
        JSONObject result = JSON.parseObject(res);
        return UploadTempResult.create(result);
    }

    /**
     * 由于不知道上传文件的编码格式，无法进行有效的转化
     **/
    public static GetTempResult getTemp(String token, String media_id, String path) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + token + "&media_id=" + media_id;
        InputStream inputStream = HttpUtil.get(url);
        String res = DataFormatUtil.fullyReadStream(inputStream);
        if (res.contains("errcode")) {
            JSONObject result = JSON.parseObject(res);
            return GetTempResult.create(result);
        } else {
            File file = new File(path);
            if (!file.exists()) {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
            }
            BufferedInputStream bis = new BufferedInputStream(HttpUtil.get(url));
            FileOutputStream fos = new FileOutputStream(path);
            int size = 0;
            byte[] buf = new byte[8096];
            while ((size = bis.read(buf)) != -1)
                fos.write(buf, 0, size);
            fos.close();
            bis.close();
            return GetTempResult.create(file);
        }
    }


    /**
     * 【订阅号与服务号认证后均可用】
     * 上传图文消息内的图片获取URL,本接口所上传的图片不占用公众号的素材库中图片数量的5000个的限制。图片仅支持jpg/png格式，大小必须在1MB以下。
     * 上传卡券LOGO
     * 尺寸640*340px
     **/
    public static UploadNewImgResult uploadNewImg(String token, File file) throws IOException {
        return uploadNewImg(token, file, file.getName());
    }

    public static UploadNewImgResult uploadNewImg(String token, File file, String fileName) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=" + token;
        String res = postFile(url, file, fileName);
        JSONObject result = JSON.parseObject(res);
        return UploadNewImgResult.create(result);
    }


    /**
     * 媒体文件类型，分别有图片（image）、语音（voice）和缩略图（thumb）
     * 图片素材的上限为5000，其他类型为1000
     **/

    public static UploadPermanentResult uploadPermanentFile(String token, String type, File file) throws IOException {
        return uploadPermanentFile(token, type, file, file.getName());
    }

    public static UploadPermanentResult uploadPermanentFile(String token, String type, InputStream inputStream,String name) throws IOException {
        if (type.equals("video")) {
            return null;
        }
        String url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + token + "&type=" + type;
        String res = postFile(url, inputStream,name);
        JSONObject result = JSON.parseObject(res);
        return UploadPermanentResult.create(result);
    }

    public static UploadPermanentResult uploadPermanentFile(String token, String type, File file, String fileName) throws IOException {
        return uploadPermanentFile(token, type, new FileInputStream(file), fileName);
    }



    /**
     * 媒体文件类型，视频（video）
     * 上限为5000
     **/
    public static UploadPermanentResult uploadPermanentVideoFile(String token, String type, File file, String title, String introduction) throws IOException {
        if (!type.equals("video")) {
            return null;
        }
        JSONObject body = new JSONObject();
        body.put("title", title);
        body.put("introduction", introduction);
        String url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + token + "&type=" + type;
        String res = postFile(url, file, null, body.toJSONString());
        JSONObject result = JSON.parseObject(res);
        return UploadPermanentResult.create(result);

    }


    /**
     * 上传永久图文信息，上限为5000
     **/
    public static UploadPermanentNewsResult uploadPermanentNews(String token, List<Article> articles) throws IOException {
        JSONObject body = new JSONObject();
        JSONArray articlesArray = new JSONArray();
        for (Article article : articles) {
            JSONObject object = JSON.parseObject(JSON.toJSONString(article));
            articlesArray.add(object);
        }
        body.put("articles", articlesArray);
        String url = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=" + token;
        InputStream inputStream = HttpUtil.post(url, body.toJSONString());
        String res = DataFormatUtil.fullyReadStream(inputStream);
        JSONObject result = JSON.parseObject(res);
        return UploadPermanentNewsResult.create(result);
    }


    /**
     * 修改永久视图信息
     *
     * @param media_id 要修改的图文消息的id
     * @param index    要更新的文章在图文消息中的位置（多图文消息时，此字段才有意义），第一篇为0
     * @param article  图文信息
     **/
    public static Result editPermanentNews(String token, String media_id, String index, Article article) throws IOException {
        JSONObject body = new JSONObject();
        body.put("media_id", media_id);
        body.put("index", index);
        body.put("articles", article);
        String url = "https://api.weixin.qq.com/cgi-bin/material/update_news?access_token=" + token;
        InputStream inputStream = HttpUtil.post(url, body.toJSONString());
        String res = DataFormatUtil.fullyReadStream(inputStream);
        JSONObject result = JSON.parseObject(res);
        return new Result(result);
    }


    /**
     * 获取永久的图文信息
     **/
    public static GetPermanentNewsResult getPermanentNews(String token, String media_id) throws IOException {
        InputStream inputStream = getPermanent(token, media_id);
        String res = DataFormatUtil.fullyReadStream(inputStream);
        JSONObject result = JSON.parseObject(res);
        return GetPermanentNewsResult.create(result);
    }

    /**
     * 获取永久的视频素材信息
     **/
    public static GetPermanentVedioResult getPermanentVedio(String token, String media_id) throws IOException {
        InputStream inputStream = getPermanent(token, media_id);
        String res = DataFormatUtil.fullyReadStream(inputStream);
        JSONObject result = JSON.parseObject(res);
        return GetPermanentVedioResult.create(result);
    }

    /**
     * 获取永久的其他素材信息
     **/
    public static GetPermanentOtherResult getPermanentOther(String token, String media_id, String path) throws IOException {
        InputStream inputStream = getPermanent(token, media_id);
        String res = DataFormatUtil.fullyReadStream(inputStream);
        if (res.contains("errcode")) {
            JSONObject result = JSON.parseObject(res);
            return GetPermanentOtherResult.create(result);
        } else {
            File file = new File(path);
            if (!file.exists()) {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
            }
            BufferedInputStream bis = new BufferedInputStream(getPermanent(token, media_id));
            FileOutputStream fos = new FileOutputStream(path);
            int size = 0;
            byte[] buf = new byte[8096];
            while ((size = bis.read(buf)) != -1)
                fos.write(buf, 0, size);
            fos.close();
            bis.close();
            return GetPermanentOtherResult.create(file);
        }
    }

    private static InputStream getPermanent(String token, String media_id) throws IOException {
        JSONObject body = new JSONObject();
        body.put("media_id", media_id);
        String url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" + token;
        InputStream inputStream = HttpUtil.post(url, body.toJSONString());
        return inputStream;
    }


    //删除永久素材
    public static Result deletePermanent(String token, String media_id) throws IOException {
        JSONObject body = new JSONObject();
        body.put("media_id", media_id);
        String url = "https://api.weixin.qq.com/cgi-bin/material/del_material?access_token=" + token;
        InputStream inputStream = HttpUtil.post(url, body.toJSONString());
        String res = DataFormatUtil.fullyReadStream(inputStream);
        JSONObject result = JSON.parseObject(res);
        return new Result(result);
    }


    //获取素材总数
    public static GetMaterialCountResult getMaterialCount(String token) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=" + token;
        InputStream inputStream = HttpUtil.get(url);
        String res = DataFormatUtil.fullyReadStream(inputStream);
        JSONObject result = JSON.parseObject(res);
        return GetMaterialCountResult.create(result);
    }

    //素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news）
    public static GetMaterialListResult getMaterialList(String token, String type, int offset, int count) throws IOException {
        JSONObject body = new JSONObject();
        body.put("type", type);
        body.put("offset", offset);
        body.put("count", count);
        String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + token;
        InputStream inputStream = HttpUtil.post(url, body.toJSONString());
        String res = DataFormatUtil.fullyReadStream(inputStream);
        JSONObject result = JSON.parseObject(res);
//            System.out.println(result);
        return GetMaterialListResult.create(type, result);
    }


}
